const Op = require('sequelize').Op
const config = require('./../../config')
const models = require('../../db/mysqldb/index')
const { createAdminSystemLog } = require('./adminSystemLog')
const logger = require('./../../utils/logger')
const { SuccessModel, ErrorModel } = require('./../../utils/index')

/**
 * 角色 控制层
 */
class AdminRoleAuthority {
  /**
   * 创建角色
   * @param {*} role_name
   * @param {*} role_description
   */
  static async createAdminRole(req, res) {
    const { role_name, role_description } = req.body
    logger.info('AdminRoleAuthority', 'createAdminRole', 'req.body', req.body)
    if (!role_name) {
      res.json(new ErrorModel([], `请输入角色名!`))
      return
    }
    if (!role_description) {
      res.json(new ErrorModel([], `请输入角色介绍!`))
      return
    }
    try {
      let admin_role_res = await models.admin_role.findOne({
        where: {
          role_name
        }
      })
      logger.info(
        'AdminRoleAuthority',
        'createAdminRole',
        'admin_role_res',
        admin_role_res
      )
      if (admin_role_res) {
        res.json(new ErrorModel([], `该角色已存在!`))
        return
      }
      let admin_role_cre = await models.admin_role.create({
        role_name,
        role_description
      })
      logger.info(
        'AdminRoleAuthority',
        'createAdminRole',
        'admin_role_cre',
        admin_role_cre
      )
      const system_log_cre = await createAdminSystemLog({
        uid: req.user.uid,
        type: 1,
        content: `${req.user.account}成功创建了‘${role_name}’角色`
      })
      logger.info(
        'AdminRoleAuthority',
        'createAdminRole',
        'system_log_cre',
        system_log_cre
      )
      res.json(new SuccessModel([], 'success'))
    } catch (error) {
      logger.info(
        'AdminRoleAuthority',
        'createAdminRole',
        'error',
        error.message
      )
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 编辑用户角色
   * @param {*} role_name
   * @param {*} role_description
   * @param {*} role_id
   */
  static async editAdminRole(req, res) {
    const { role_name, role_description, role_id } = req.body
    logger.info('AdminRoleAuthority', 'editAdminRole', 'req.body', req.body)
    if (!role_name) {
      res.json(new ErrorModel([], `请输入角色名!`))
      return
    }
    if (!role_description) {
      res.json(new ErrorModel([], `请输入角色介绍!`))
      return
    }
    if (!role_id) {
      res.json(new ErrorModel([], `请输入角色id!`))
      return
    }
    try {
      const admin_role_has = await models.admin_role.findOne({
        where: {
          role_name,
          role_id: {
            [Op.ne]: role_id
          }
        }
      })
      logger.info(
        'AdminRoleAuthority',
        'editAdminRole',
        'admin_role_has',
        admin_role_has
      )
      if (admin_role_has) {
        res.json(new ErrorModel([], `该角色已存在!`))
        return
      }
      const admin_role_upd = await models.admin_role.update(
        {
          role_name,
          role_description
        },
        {
          where: {
            role_id
          }
        }
      )
      logger.info(
        'AdminRoleAuthority',
        'editAdminRole',
        'admin_role_upd',
        admin_role_upd
      )
      const system_log_cre = await createAdminSystemLog({
        uid: req.user.uid,
        type: 2,
        content: `${req.user.account}成功更新了id为‘${role_id}’的角色‘${role_name}’`
      })
      logger.info(
        'AdminRoleAuthority',
        'editAdminRole',
        'system_log_cre',
        system_log_cre
      )
      res.json(new SuccessModel([], `角色修改成功`))
    } catch (error) {
      logger.info(
        'AdminRoleAuthority',
        'createAdminRole',
        'error',
        error.message
      )
      res.json(new ErrorModel([], error.message))
    }
  }
  /**
   * 删除角色
   * @param {*} role_id
   */
  static async deleteAdminRole(req, res) {
    const { role_id } = req.body
    logger.info('AdminRoleAuthority', 'deleteAdminRole', 'req.body', req.body)
    if (!role_id) {
      res.json(new ErrorModel([], `请输入角色id!`))
      return
    }
    if (role_id === config.SUPER_ROLE_ID) {
      res.json(new ErrorModel([], `该角色无法删除`))
      return
    }
    try {
      // 根据role_id查找用户表 判断是否有绑定此角色的用户
      const admin_user_find = await models.admin_user.findAll({
        where: {
          admin_role_ids: role_id
        }
      })
      logger.info(
        'AdminRoleAuthority',
        'deleteAdminRole',
        'admin_user_find',
        admin_user_find
      )
      if (admin_user_find) {
        let userArr = []
        for (const key in admin_user_find) {
          if (admin_user_find.hasOwnProperty(key)) {
            userArr.push(admin_user_find[key].account)
          }
        }
        let users = userArr.join(',')
        res.json(new ErrorModel([], `该角色绑定了${users}等角色`))
        return
      }
      // 删除角色
      const admin_role_del = await models.admin_role.destroy({
        where: { role_id }
      })
      logger.info(
        'AdminRoleAuthority',
        'deleteAdminRole',
        'admin_role_del',
        admin_role_del
      )
      // 插入删除日志
      const system_log_cre = await createAdminSystemLog({
        uid: req.user.uid,
        type: 3,
        content: `${req.user.account}成功删除了id为‘${role_id}’的角色’`
      })
      logger.info(
        'AdminRoleAuthority',
        'deleteAdminRole',
        'system_log_cre',
        system_log_cre
      )
      res.json(new SuccessModel([], `角色删除成功`))
    } catch (error) {
      logger.info(
        'AdminRoleAuthority',
        'deleteAdminRole',
        'error',
        error.message
      )
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 获取权限分页数据
   * @param {*} page
   * @param {*} limit
   */
  static async getAdminRoleList(req, res) {
    const { page = 1, limit = 10 } = req.query
    logger.info(
      'AdminRoleAuthority',
      'getAdminRoleList',
      'req.query',
      req.query
    )
    try {
      let { count, rows } = await models.admin_role.findAndCountAll({
        attributes: [
          'role_id',
          'role_name',
          'role_description',
          'admin_authority_ids'
        ],
        where: '',
        offset: (Number(page) - 1) * Number(limit),
        limit: Number(limit)
      })
      logger.info('AdminRoleAuthority', 'getAdminRoleList', 'count', count)
      logger.info('AdminRoleAuthority', 'getAdminRoleList', 'rows', rows)
      res.json(new SuccessModel({ count, rows }, '返回成功'))
    } catch (error) {
      logger.info(
        'AdminRoleAuthority',
        'getAdminRoleList',
        'error',
        error.message
      )
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 获取权限所有数据
   * @param {*} req
   * @param {*} res
   */
  static async getAdminRoleAll(req, res) {
    try {
      let adminRoleAll = await models.admin_role.findAll()
      logger.info(
        'AdminRoleAuthority',
        'getAdminRoleAll',
        'adminRoleAll',
        adminRoleAll
      )
    } catch (error) {
      logger.info(
        'AdminRoleAuthority',
        'getAdminRoleAll',
        'error',
        error.message
      )
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 创建权限
   * @param {*} req
   */
  static async createAdminAuthority(req, res) {
    const {
      authority_name,
      authority_type,
      authority_parent_id,
      authority_parent_name,
      authority_url,
      authority_sort,
      authority_description,
      enable
    } = req.body
    logger.info(
      'AdminRoleAuthority',
      'createAdminAuthority',
      'req.body',
      req.body
    )
    if (!authority_name) {
      res.json(new ErrorModel([], `请输入权限名称`))
      return
    }
    if (!authority_url) {
      res.json(new ErrorModel([], `请输入权限路径`))
      return
    }
    try {
      let admin_authority_one = await models.admin_authority.findOne({
        where: {
          authority_name
        }
      })
      logger.info(
        'AdminRoleAuthority',
        'createAdminAuthority',
        'admin_authority_one',
        admin_authority_one
      )

      if (admin_authority_one) {
        res.json(new ErrorModel([], `权限名已存在`))
        return
      }

      let admin_authority_one_url = await models.admin_authority.findOne({
        where: {
          authority_url
        }
      })
      if (admin_authority_one_url) {
        res.json(new ErrorModel([], `权限路径已存在`))
        return
      }
      logger.info(
        'AdminRoleAuthority',
        'createAdminAuthority',
        'admin_authority_one_url',
        admin_authority_one_url
      )
      const admin_authority_cre = await models.admin_authority.create({
        authority_name,
        authority_type,
        authority_parent_id,
        authority_parent_name,
        authority_url,
        authority_sort,
        authority_description,
        enable: enable || true
      })
      logger.info(
        'AdminRoleAuthority',
        'createAdminAuthority',
        'admin_authority_cre',
        admin_authority_cre
      )
      // 插入日志
      const system_log_cre = await createAdminSystemLog({
        uid: req.user.uid,
        type: 1,
        content: `${req.user.account}成功插入了名称为‘${authority_name}’的权限’`
      })
      logger.info(
        'AdminRoleAuthority',
        'createAdminAuthority',
        'system_log_cre',
        system_log_cre
      )
      res.json(new SuccessModel([], `权限生成成功`))
    } catch (error) {
      logger.info(
        'AdminRoleAuthority',
        'createAdminAuthority',
        'error',
        error.message
      )
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 获取权限列表
   * @param {*} req
   * @param {*} res
   */
  static async getAdminAuthorityAllList(req, res) {
    try {
      let admin_authority_all = await models.admin_authority.findAll()
      logger.info(
        'AdminRoleAuthority',
        'getAdminAuthorityAllList',
        'admin_authority_all',
        admin_authority_all
      )
      res.json(new SuccessModel(admin_authority_all, 'success'))
    } catch (error) {
      logger.info(
        'AdminRoleAuthority',
        'getAdminAuthorityAllList',
        'error',
        error.message
      )
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 修改权限
   * @param {*} req
   */
  static async updateAdminAuthority(req, res) {
    const {
      authority_id,
      authority_name,
      authority_type,
      authority_url,
      authority_sort,
      authority_description,
      enable
    } = req.body
    logger.info(
      'AdminRoleAuthority',
      'updateAdminAuthority',
      'req.body',
      req.body
    )
    try {
      let admin_authority_one = await models.admin_authority.findOne({
        where: {
          authority_name,
          authority_id: {
            [Op.ne]: authority_id
          }
        }
      })
      logger.info(
        'AdminRoleAuthority',
        'updateAdminAuthority',
        'admin_authority_one',
        admin_authority_one
      )
      if (admin_authority_one) {
        res.json(new ErrorModel([], `权限名已存在`))
        return
      }

      let admin_authority_one_url = await models.admin_authority.findOne({
        where: {
          authority_url,
          authority_id: {
            [Op.ne]: authority_id
          }
        }
      })
      if (admin_authority_one_url) {
        res.json(new ErrorModel([], `权限路径已存在`))
        return
      }
      logger.info(
        'AdminRoleAuthority',
        'updateAdminAuthority',
        'admin_authority_one_url',
        admin_authority_one_url
      )
      const admin_authority_upd = await models.admin_authority.update(
        {
          authority_name,
          authority_type,
          authority_url,
          authority_sort,
          authority_description,
          enable
        },
        {
          where: {
            authority_id
          }
        }
      )
      logger.info(
        'AdminRoleAuthority',
        'updateAdminAuthority',
        'admin_authority_upd',
        admin_authority_upd
      )
      // 插入日志
      const system_log_cre = await createAdminSystemLog({
        uid: req.user.uid,
        type: 2,
        content: `${req.user.account}成功更新了名称为‘${authority_name}’的权限’`
      })
      logger.info(
        'AdminRoleAuthority',
        'updateAdminAuthority',
        'system_log_cre',
        system_log_cre
      )
      res.json(new SuccessModel([], `权限生成成功`))
    } catch (error) {
      logger.info(
        'AdminRoleAuthority',
        'updateAdminAuthority',
        'error',
        error.message
      )
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 删除权限列表
   * @param {*} req
   * @param {*} res
   */
  static async deleteAdminAuthority(req, res) {
    const { authority_id_arr } = req.body
    logger.info(
      'AdminRoleAuthority',
      'deleteAdminAuthority',
      'req.body',
      req.body
    )
    try {
      if (!authority_id_arr.length) {
        res.json(new ErrorModel(`传参有误`))
      }
      const admin_authority_del = await models.admin_authority.destroy({
        where: {
          authority_id: {
            [Op.in]: authority_id_arr
          }
        }
      })
      logger.info(
        'AdminRoleAuthority',
        'deleteAdminAuthority',
        'admin_authority_del',
        admin_authority_del
      )
      const authority_ids = authority_id_arr.join(',')
      const system_log_cre = await createAdminSystemLog({
        uid: req.user.uid,
        type: 3,
        content: `${req.user.account}成功删除了id分别为‘${authority_id_arr}’的权限’`
      })
      logger.info(
        'AdminRoleAuthority',
        'updateAdminAuthority',
        'system_log_cre',
        system_log_cre
      )
      res.json(new SuccessModel([], '删除成功'))
    } catch (error) {
      logger.info(
        'AdminRoleAuthority',
        'deleteAdminAuthority',
        'error',
        error.message
      )
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 角色用户关联
   * @param {string} uid
   * @param {string} role_id
   */
  static async createAdminUserRole(req, res) {
    const { uid, role_id } = req.body
    logger.info(
      'AdminRoleAuthority',
      'createAdminUserRole',
      'req.body',
      req.body
    )
    try {
      const admin_user_upd = await models.admin_user.update(
        {
          admin_role_ids: role_id
        },
        {
          where: {
            uid
          }
        }
      )
      logger.info(
        'AdminRoleAuthority',
        'createAdminUserRole',
        'admin_user_upd',
        admin_user_upd
      )
      res.json(new SuccessModel([], `绑定角色成功`))
    } catch (error) {
      logger.info(
        'AdminRoleAuthority',
        'createAdminUserRole',
        'error',
        error.message
      )
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 角色权限关联
   * @param {*} role_id
   * @param {*} role_authority_list_all
   */
  static async setAdminRoleAuthority(req, res) {
    const { role_id, role_authority_list_all } = req.body
    logger.info(
      'AdminRoleAuthority',
      'setAdminRoleAuthority',
      'req.body',
      req.body
    )
    try {
      const admin_role_upd = await models.admin_role.update(
        {
          admin_authority_ids: role_authority_list_all.json(',')
        },
        {
          where: {
            role_id
          }
        }
      )
      logger.info(
        'AdminRoleAuthority',
        'setAdminRoleAuthority',
        'admin_role_upd',
        admin_role_upd
      )
      res.json(new SuccessModel([], `角色权限关联成功`))
    } catch (error) {
      logger.info(
        'AdminRoleAuthority',
        'setAdminRoleAuthority',
        'error',
        error.message
      )
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 根据用户权限获取菜单
   */
  static async getMenu(req, res) {
    const { user } = req
    logger.info('AdminRoleAuthority', 'getMenu', 'req.user', req.user)
    try {
      const { role_id } = user
      const role_req = await models.admin_role.findOne({
        where: {
          role_id
        }
      })
      logger.info('AdminRoleAuthority', 'getMenu', 'role_req', role_req)
      const admin_authority_ids_arr = role_req.admin_authority_ids.split(',')
      logger.info(
        'AdminRoleAuthority',
        'getMenu',
        'admin_authority_ids_arr',
        admin_authority_ids_arr
      )
      const admin_authority_req = await models.admin_authority.findAll({
        attributes: [
          'id',
          'authority_id',
          'authority_name',
          'authority_parent_id',
          'authority_parent_name',
          'authority_url',
          'authority_sort',
          'authority_type',
          'icon'
        ],
        where: {
          // authority_id: {
          //   [Op.in]: admin_authority_ids_arr
          // },
          authority_type: '1',
          enable: 0
        }
      })
      logger.info(
        'AdminRoleAuthority',
        'getMenu',
        'admin_authority_req',
        admin_authority_req
      )
      res.json(new SuccessModel(admin_authority_req, 'success'))
    } catch (error) {
      logger.info('AdminRoleAuthority', 'getMenu', 'error', error.message)
      res.json(new ErrorModel([], error.message))
    }
  }

  /**
   * 菜单树
   */
  static async getMenuTree(req, res) {
    const { user } = req
    logger.info('AdminRoleAuthority', 'getMenu', 'req.user', req.user)
    try {
      const { role_id } = user
      const role_req = await models.admin_role.findOne({
        where: {
          role_id
        }
      })
      logger.info('AdminRoleAuthority', 'getMenu', 'role_req', role_req)
      const admin_authority_ids_arr = role_req.admin_authority_ids.split(',')
      logger.info(
        'AdminRoleAuthority',
        'getMenu',
        'admin_authority_ids_arr',
        admin_authority_ids_arr
      )
      const admin_authority_req = await models.admin_authority.findAll({
        attributes: [
          'id',
          'authority_id',
          'authority_name',
          'authority_parent_id',
          'authority_parent_name',
          'authority_url',
          'authority_sort',
          'authority_type',
          'icon'
        ],
        where: {
          // authority_id: {
          //   [Op.in]: admin_authority_ids_arr
          // },
          authority_type: '1',
          enable: 0
        }
      })
      logger.info(
        'AdminRoleAuthority',
        'getMenu',
        'admin_authority_req',
        admin_authority_req
      )
      res.json(new SuccessModel(admin_authority_req, 'success'))
    } catch (error) {
      logger.info('AdminRoleAuthority', 'getMenu', 'error', error.message)
      res.json(new ErrorModel([], error.message))
    }
  }
}
module.exports = {
  AdminRoleAuthority
}
